// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-01

package mobile

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/logics/guest"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
)

// Logic
// 获取手机号.
type Logic struct {
	request  *Request
	response *Response

	guest.Login
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	return validator.Json(i, o.request)
}

// Run
// 登陆过程.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err     error
		has     bool
		logined *guest.Logined
		mobile  kind.Mobile
		oauth   *models.Oauth
		res     = result.New()
	)

	// 1. 查询授权.
	if oauth, has, err = services.NewOauthService().Dao.GetById(ctx, o.request.AuthId); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2. 无效授权.
	if !has || oauth.UserCode != o.request.UserCode {
		return res.WithError(errs.ErrUserOauthNotFound)
	}

	// 3. 读取号码.
	if mobile, err = lib.Weixin.GetMobile(ctx, o.request.Code); err != nil {
		return res.WithError(err)
	}

	// 4. 保存号码.
	if _, err = services.NewOauthService().Dao.UpdateFieldsById(ctx, map[string]any{
		"open_mobile": mobile,
	}, oauth.Id); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 5. 检查绑定.
	logined = &guest.Logined{}
	logined.Mobile = mobile.Mask()
	return res.With(logined)
}
